<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\constant\Common;
use plugin\wechat\app\model\BotGroupmember;
use plugin\wechat\app\model\BotMember;
use plugin\wechat\app\model\BotForward as ForwardM;
use Support\Request;
use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\BotFriend as FriendService;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\service\BotForward as  ForwardService;

class Botforward extends BotBase
{
    /**
     * @var ForwardM
     */
    protected $model;
    /**
     * @var BotGroupmember
     */
    private $groupMemberM;
    /**
     * @var BotMember
     */
    private $memberM;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new ForwardM();
        $this->groupMemberM = new BotGroupmember();
        $this->memberM = new BotMember();
    }

    protected function tabList(){
        return [
            'group' => ['title' => '新增群聊转播', 'href' => url('add', ['type' => 'group'])],
            'private' => ['title' => '新增私聊转播', 'href' => url('add', ['type' => 'private'])],
        ];
    }

    /**
     * 转发列表
     * @param Request $request
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(Request $request)
    {
        $bot = $request->botInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere('g'),
                ['g.bot_id' ,'=', $bot['id']],
            ];

            $query = $this->model->alias('g')
                ->join($request->plugin . '_bot_member m', 'm.id=g.group_id', 'left')
                ->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('g.update_time', 'desc')
                    ->field(['g.id','m.nickname as group_title', 'g.officer', 'group_id','g.status','g.wxids'])
                    ->select();
                foreach ($list as $k => $v){
                    if($v['group_id']){
                        $group_members = $this->groupMemberM->where([
                            ['wxid' , 'in', $v['officer']],
                            ['group_id' ,'=', $v['group_id']]
                        ])
                            ->column('nickname');
                        $v['officer_names'] = implode(',', $group_members);
                    }else{
                        $v['group_title'] = '---';
                        if($officer = $this->memberM->where('wxid' ,$v['officer'])->find()){
                            $v['officer_names'] = $officer['nickname'];
                        }else{
                            $v['officer_names'] = '---';
                        }
                    }
                    $members = array_unique($this->memberM->where([
                        ['wxid' ,'in', $v['wxids']],
                        ['uin' ,'=', $bot['uin']]
                    ])
                        ->column('nickname'));
                    if(($count = count($members)) > 1){
                        $v['wxids'] = $members[0] . '等'.$count.'个';
                    }else{
                        $v['wxids'] = empty($members[0]) ? "---" : $members[0];
                    }
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
        $builder = new ListBuilder();
        $builder->addTopButton('addnew', ['text' => '新增转播','title' => '新增转播'])
                ->addTableColumn(['title' => '序号', 'field' => 'id', 'type' => 'index','minWidth' => 70])
                ->addTableColumn(['title' => '主讲群', 'field' => 'group_title', 'minWidth' => 150])
                ->addTableColumn(['title' => '主讲人', 'field' => 'officer_names', 'minWidth' => 200])
                ->addTableColumn(['title' => '发送对象', 'field' => 'wxids', 'minWidth' => 200])
                ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'switch', 'options' => Common::yesOrNo(),'minWidth' => 60])
                ->addTableColumn(['title' => '操作', 'minWidth' => 70, 'type' => 'toolbar'])
                ->addRightButton('edit');
        return $builder->show();
    }

    private function getOfficers(){
        $groups = $this->memberM->where([
            ['uin', '=', \request()->botInfo['uin']],
            ['type', '=', BotService::GROUP]
        ])->column(['id','nickname as title']);
        foreach ($groups as $k => $v){
            $v['children'] = $this->groupMemberM->where('group_id', $v['id'])
                ->column(['nickname as title', 'wxid as id']);
            $groups[$k] = $v;
        }
        return $groups;
    }

    /**
     * 新增
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $bot = \request()->botInfo;
        $type = input('type', 'group');
        $data = ['bot_id' => $bot['id'], 'status' => 1];
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->setTabNav($this->tabList(), $type)
            ->addFormItem('bot_id', 'hidden', 'bot_id', 'bot_id');
        if($type == 'private'){
            $builder->addFormItem('officer', 'chosen', '主讲人', '选择主讲人', FriendService::getWxidToNickname(null, [['type','=', BotService::FRIEND]]), 'required');
        }else{
            $builder->addFormItem('officer', 'linkage', '主讲群&人', '选择主讲人', ['data' => $this->getOfficers()], 'required');
        }

        $builder->addFormItem('wxids', 'chosen_multi', '转发到', '消息接收方', FriendService::getWxidToNickname(), 'required')
            ->addFormItem('status', 'radio', '转发状态', '转发状态', [1=>'转发', 0 => '暂停'], 'required')
            ->setFormData($data);
        return $builder->show();
    }

    /**
     * 编辑
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(){
        $id = input('id', null);
        $data = $this->model->where([$this->tenantWhere()])
            ->find($id);

        if (!$data) {
            return $this->error('参数错误');
        }
        $data['wxids'] = explode(',', $data['wxids']);
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id');
        if(! $data['group_id']){
            $builder->addFormItem('officer', 'chosen', '主讲人', '选择主讲人', FriendService::getWxidToNickname(null, BotService::FRIEND), 'required');
        }else{
            $builder->addFormItem('officer', 'linkage', '主讲人&群', '选择主讲人', ['data' => $this->getOfficers(), 'values' => [$data['group_id'], $data['officer']]], 'required');
        }
        $builder->addFormItem('wxids', 'chosen_multi', '转发到', '消息接收方', FriendService::getWxidToNickname(), 'required')
            ->addFormItem('status', 'radio', '转发状态', '转发状态', [1=>'转发', 0 => '暂停'], 'required')
            ->setFormData($data);
        return $builder->show();
    }

    /**
     * 保存
     * @param Request $request
     * @param string $jump_to
     * @param array $data
     * @return mixed|\support\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function savePost(Request $request, $jump_to = '', $data = [])
    {
        $bot = $request->botInfo;
        $post_data = input('post.');
        $post_data['company_id'] = TenantService::getCompanyId();
        $post_data['bot_id'] = $bot['id'];
        if(strpos($post_data['officer'], ',') !== false){
            list($group_id, $officer) = explode(',', $post_data['officer']);
            $post_data['group_id'] = $group_id;
            $post_data['officer'] = $officer;
        }
        if(empty($post_data[$this->pk])){
            $res = $this->model->createOne($post_data);
        }else {
            $res = $this->model->update($post_data);
        }
        if($res){
            if(!empty($res['group_id'])){
                $group = FriendService::getMemberById($res['group_id']);
                $group_wxid = $group['wxid'];
            }else{
                $group_wxid = '';
            }
            ForwardService::getGather([
                'group_wxid' => $group_wxid,
                'from_wxid' => $res['officer'],
                'bot_wxid' => $bot['uin'],
                'refresh' => true
            ]);
            return $this->success('操作成功!', $jump_to);
        }else{
            return $this->error('操作失败!', '', ['token' => token()]);
        }
    }

    /**
     * 设置一条或者多条数据的状态
     * @Author  fudaoji<fdj@kuryun.cn>
     */
    public function setStatus() {
        $ids = input('ids');
        $status = input('status', 'status');

        if (empty($ids)) {
            return $this->error('请选择要操作的数据');
        }

        $ids = (array) $ids;
        if($status == 'delete'){
            $where = [[$this->pk, 'in', $ids]];
            $this->insertCompanyId && $where[] = $this->tenantWhere();
            if($this->model->where($where)->delete()){
                return $this->success('删除成功');
            }else{
                return $this->error('删除失败');
            }
        }else{
            $bot = \request()->botInfo;
            $msg = [
                'success' => '操作成功！',
                'error'   => '操作失败！',
            ];
            $data['status'] = abs(input('val', 0) - 1);
            $this->insertCompanyId && $data['company_id'] = TenantService::getCompanyId();
            foreach($ids as $id){
                $data[$this->pk] = $id;
                $this->model->update($data);

                //refresh
                $res = $this->model->find($id);
                if(!empty($res['group_id'])){
                    $group = FriendService::getMemberById($res['group_id']);
                    $group_wxid = $group['wxid'];
                }else{
                    $group_wxid = '';
                }
                ForwardService::getGather([
                    'group_wxid' => $group_wxid,
                    'from_wxid' => $res['officer'],
                    'bot_wxid' => $bot['uin'],
                    'refresh' => true
                ]);
            }
            return $this->success($msg['success']);
        }
    }
}